import React, { useRef } from 'react'
import css from './index.module.scss'
import type { TabsItemProps, TabsProps } from './data'
import { useReactive } from '@/hooks'
/*
 * @Author: LiuYan 15136056318@163.com
 * @Date: 2023-12-06 11:29:31
 * @LastEditors: LiuYan 15136056318@163.com
 * @LastEditTime: 2023-12-07 18:30:26
 * @FilePath: \react-template_pc\src\components\tabs\index.tsx
 * @Description:
 */
interface onClickParams {
  index: number
}
interface TabsType {
  tabsAction: React.ReactNode
}
const tabs = (props: TabsProps) => {
  const { children, style, className = '', onChange, defaultActiveIndex = 0 } = props
  const Children: React.ReactNode[] = []
  const tabsRef = React.useRef<any>(null)
  const itemActiveRef = React.useRef<any>(null)
  const { state } = useReactive<TabsType>({
    tabsAction: <></>,
  })
  const onClick = (el: HTMLElement, { index }: onClickParams) => {
    const target = el
    const targetActive = itemActiveRef.current as HTMLElement
    if (targetActive) {
      targetActive.style.left = target.offsetLeft + 'px'
    }
    if (onChange) {
      state.tabsAction = onChange(index, target)
    }
    setTop(target)
  }
  children.forEach((child: any, index: number) => {
    React.Children.forEach(child, (item: any) => {
      const typeName = item?.type?.prototype?.typeName
      if (typeName && typeName == 'tabs.item') {
        Children.push(
          React.cloneElement(item, {
            key: item.key ? item.key : typeName + index,
            onClick,
            index,
          })
        )
      }
    })
  })

  const setTop = (target: HTMLElement) => {
    const tabs = tabsRef.current as HTMLElement
    tabs.scrollLeft = target.offsetLeft - tabs.clientWidth / 2.4
  }
  React.useEffect(() => {
    const tabs = tabsRef.current as HTMLElement
    const targetActive = itemActiveRef.current as HTMLElement
    const defaultActive = tabs.children[defaultActiveIndex] as HTMLElement
    setTop(defaultActive)
    if (targetActive) {
      targetActive.style.left = defaultActive.offsetLeft + 'px'
    }
    if (onChange) {
      state.tabsAction = onChange(defaultActiveIndex, defaultActive)
    }
  }, [])
  return (
    <>
      <div ref={tabsRef} className={`${css.tabs} ${className}`} style={style}>
        {Children}
        <div ref={itemActiveRef} className={`${css.tabsLine}`}>
          {state.tabsAction}
        </div>
      </div>
    </>
  )
}
tabs.item = function (props: TabsItemProps): React.ReactNode {
  const { children, style, className = '', onClick, index } = props
  const el = useRef<any>(null)
  return (
    <>
      <div
        ref={el}
        onClick={() => {
          if (onClick) onClick(el.current, { index })
        }}
        style={style}
        className={`${css.tabsItem} ${className}`}
      >
        {children}
      </div>
    </>
  )
}
tabs.item.prototype.typeName = 'tabs.item'
export default tabs
